/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="table-data">
        <sf-grid>
            <sf-toolbar ref="toolbar">
                <sf-button
                    ref="submit"
                    class="creat-button btn-blank"
                    icon-cls="iconrefresh"
                    @click="_refresh">
                    <lang>刷新</lang>
                </sf-button>
                <sf-searchfield v-model="searchParams.keyword"
                                class="pull-right" 
                                placeholder="请输入关键字"
                                @clear="onEnterkey"
                                @trigger="onEnterkey" />
            </sf-toolbar>
            <sf-table 
                ref="updateTimeTable" 
                :options="options_fix"
                @pagechange="_onPageChange"
                @sizechange="_onSizeChange">
                <sf-table-column :default-width="30"
                                 type="index">
                    <lang>序号</lang>
                </sf-table-column>
                    
                <sf-table-column data-index="taskName"
                                 :default-width="40">
                    <lang>任务名称</lang>
                </sf-table-column>
                <sf-table-column data-index="flowName"
                                 :default-width="80">
                    <lang>FLOW</lang>
                </sf-table-column>
                <sf-table-column data-index="input"
                                 :default-width="100">
                    <lang>输入</lang>
                </sf-table-column>
                <sf-table-column data-index="run_time"
                                 :default-width="80">
                    <lang>运行环境</lang>
                </sf-table-column>
                <sf-table-column data-index="createTime"
                                 :default-width="80">
                    <lang>开始时间</lang>
                </sf-table-column>
                <sf-table-column data-index="statusDetail"
                                 :default-width="60">
                    <lang>状态</lang>
                </sf-table-column>
                <sf-table-column data-index="opr"
                                 :default-width="120">
                    <lang>操作</lang>
                </sf-table-column>
                <!-- <template slot="status"
                          slot-scope="{record}">
                    <div class="task-flex"
                         :class="repositoryStatusClass(record.status)">
                        <span class="status-img task-common"></span>
                        <span class="status-text">{{ repositoryStatusText(record.status) }}</span>
                    </div>
                </template> -->
                <template slot="flowName"
                          slot-scope="{record}">
                    <span v-if="record.isFlowDeleted"
                          :title="_('该AI Flow已被删除')"
                          class="line-through">{{ record.flowName }}</span>
                    <span v-else
                          :title="record.flowName">{{ record.flowName }}</span>
                </template>
                <template slot="createTime"
                          slot-scope="{record}">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="input"
                          slot-scope="{record}">
                    <div class="algo-detail">
                        <div class="m-b5">
                            算法模板：{{ record.algoName }}
                        </div>
                        <!-- <div class="sfv-ellipsis"
                             :title="getAlgoParams(record.configJson)">
                            {{ getAlgoParams(record.configJson) }}
                        </div> -->
                    </div>
                </template>
                <template slot="run_time"
                          slot-scope="{record}">
                    <div class="run-time__list">
                        <div class="run-time">
                            <span class="name">CPU:</span>
                            <span class="value">{{ record.cpuNum }}核</span>
                        </div>
                        <div class="run-time">
                            <span class="name">GPU:</span>
                            <span class="value">{{ record.gpuNum }}个</span>
                        </div>
                        <div class="run-time">
                            <span class="name">内存:</span>
                            <span class="value">{{ record.memorySize }}GB</span>
                        </div>
                    </div>
                </template>
                <template slot="statusDetail"
                          slot-scope="{record}">
                    <div class="run-time__list">
                        <div class="run-time">
                            <span class="name">总数:</span>
                            <span class="value">{{ statusDetailJson(record).sum }}</span>
                        </div>
                        <div class="run-time success">
                            <span class="name">成功:</span>
                            <span class="value">{{ statusDetailJson(record).succeeded }}</span>
                        </div>
                        <div class="run-time running">
                            <span class="name">运行中:</span>
                            <span class="value">{{ statusDetailJson(record).running }}</span>
                        </div>
                        <div class="run-time failed">
                            <span class="name">失败:</span>
                            <span class="value">{{ statusDetailJson(record).failed }}</span>
                        </div>
                    </div>
                </template>
                <template slot="opr"
                          slot-scope="{record}">
                    <div class="opr">
                        <!-- <sf-button
                            ref="submit"
                            size="small"
                            class="creat-button m-r5"
                            :default-disabled="!record.s3Address"
                            @click="_registryModel(record)">
                            <lang>注册模型</lang>
                        </sf-button> -->
                        <sf-button class="m-r5"
                                   size="small"
                                   @click="_previewStatus(record)">
                            <lang>查看日志</lang>
                        </sf-button>
                        <a 
                            v-if="record.isFlowDeleted"
                            class="link-btn"
                            :class="{'disabled': record.isFlowDeleted}"
                            @click="_updateModel(record)">
                            <lang>编辑</lang>
                        </a>
                        <a 
                            v-else
                            class="link-btn"
                            @click="_updateModel(record)">
                            <lang>编辑</lang>
                        </a>
                        <!-- <a 
                            class="link-btn"
                            :title="_('该AI Flow已被删除')"
                            >
                            <lang>查看详情</lang>
                        </a> -->
                        <a 
                            class="link-btn"
                            :class="{'disabled': record.status !== 0}"
                            @click="getAIPreviewFlowSnapShot(record)">
                            <lang>查看详情</lang>
                        </a>
                        <a 
                            class="link-btn"
                            @click="_deleteModel(record)">
                            <lang>删除</lang>
                        </a>
                    </div>
                </template>
            </sf-table>
        </sf-grid>
        <sf-drawer
            :title="title"
            :visible.sync="showHistroyDrawer"
            :size="drawWidth"
            custom-class="task-detail__container"
            :direction="direction">
            <div class="task-preview-detail__container">
                <task-detail :detail-data="taskDetailData"
                             :registry-params="registryParams" />
                <!-- <sf-tab-panel ref="optionsTabpanel"
                              class="detail-tab"
                              size="large"
                              :tab-width="48"
                              :title-hide="true">
                    <sf-tab-item :title="_('特征处理')">
                        <preview-feature :rule-graph-list="ruleGraphList" />
                    </sf-tab-item>
                    <sf-tab-item :title="_('模型训练')">
                        <training-detail :training-info="trainingInfo" />
                    </sf-tab-item>
                </sf-tab-panel> -->
            </div>
        </sf-drawer>
    </div>
</template>
<script>
import {
    encodeDate
} from 'src/util/format';
import parseJson from 'src/util/parse_json.ts';
import store from 'src/vuex/store';
let userID = store.state.userId;
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
import { deepClone } from 'src/util/deep_clone';
const RUN_STATUS_URL = trainingUrlAdapter(`user/${userID}/task/run/status`);


// let algorithmByLayerURL = trainingUrlAdapter('algorithm/algorithmByLayer');
// import updateModelForm from './label_form/update_model_form.vue';
import IntervalTask from 'src/util/interval_task';

// const ALGORITHM_LIST = 'training/v1/model/algorithm';

/*训练状态*/
const REPOSITORY_STATUS_TEXT = {
    0:_('任务完成'),
    1:_('任务中'),
    2:_('任务失败')
};
const REPOSITORY_STATUS_CLASS = {
    0:'task-success',
    1:'task-run',
    2:'task-fail'
};


// import PreviewFeature from 'src/home/mod_cluster/project_manager/components/common/preview/preview_feature.vue';
// import TrainingDetail from 'src/home/mod_cluster/project_manager/components/common/preview/training_detail.vue';

import TaskDetail from './label_form/task_detail.vue';

// const FLOW_URL = {
//     review:trainingUrlAdapter('flow/-/snapshot'),
// };
const PAGE_COUNT = 8;

import selectDataTransfrom from 'src/util/select_transform.ts';

import TaskLogTable from './label_form/task_log_table.vue';

export default {
    name: 'SingerUpdateTable',
    components:{

        // PreviewFeature,
        // TrainingDetail,
        TaskDetail
    },
    data () {
        return {
            gridOptions: {
                rowCls (record) {
                    return !record.isGroup ? 'is-child-row' : '';
                },
                data: []
            },
            searchParams: {
                keyword: '',
                algorithmName:'',
                pageSize: PAGE_COUNT,
                pageNum: 0
            },
            defaultWidth:200,
            algorith_id:0,
            algorithmList:[{
                label:_('全部算法模板'),
                value:0
            }],
            intervalTask:null,
            showEmptytraining:false,
            emptyText:_('没有找到对应的模型'),
            options_fix: {
                bufferView: false,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                selectionHide: true,
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')],
                    layout: [ 'pager', 'sizes', 'jumper']
                }
            },
            trainingIdList:[],
            isGetTrainingStatus:false,
            title: _('查看详情'),
            showHistroyDrawer:false,
            direction : 'rtl',
            trainingInfo : {},
            ruleGraphList : [],
            taskDetailData:[],
            registryParams:{} 
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        },
        drawWidth () {
            return 'calc(100% - 400px)';
        }
    },
    mounted () {
        this.refreshGrid();
        this._createIntervalTask();
    },
    methods: {

          // 创建查看日志功能
        _createtaskLogTableFormWin () {
            if (!this.taskLogTableFormWin) {
                this.taskLogTableFormWin = this.$modal(TaskLogTable, {
                    autoDestory: true
                });
            }
            return this.taskLogTableFormWin;
        },
        async _previewStatus (record) {

            const TABLE_LOG_URL = trainingUrlAdapter(`task/${record.id}/workflow`);
            this.$mask();
            let jsonData = await this.$ajax.get(TABLE_LOG_URL);
            this.$unmask();
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            };
            let formWin = this._createtaskLogTableFormWin();
            formWin.formRoot.setJsonValue(data, record.id);
            formWin.open({
                title: _('查看日志'),
                buttons: [{
                    cls: 'btn-default',
                    text: '关闭',
                    actionName: 'cancel'
                }]
            });
        },

       
         
        statusDetailJson (jsons) {
            return  parseJson(jsons.statusDetail);
        },

        //获取图规则
        async getAIPreviewFlowSnapShot (params) {
            let getSnapShotURL = trainingUrlAdapter(`task/${params.id}/detail`);

            //  let getGraphURL = `${GRAPG_URL.get}/4`;
            let jsonData = await this.$ajax.get(getSnapShotURL);
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            };
            this.showHistroyDrawer = true;
            this.taskDetailData = data;
            this.registryParams = params;
        },

        // async _getAlgorithmList () {
        //     let jsonData = await this.$ajax.get(ALGORITHM_LIST);
        //     let {success, msg} = jsonData;
        //     if (!success) {
        //         this.$showErr(msg || _('加载数据失败'));
        //         return;
        //     }
            
        // },
        _createIntervalTask () {
            let vm = this;
            this.intervalTask = new IntervalTask({
                fn: () => {
                    vm._refreshTrainingStatus().then(() => {
                        vm.intervalTask && vm.intervalTask.next();
                    });
                },
                interval: 5000,
                autoStart: true
            });
        },

        onEnterkey () {
            this.refreshGrid();
        },

        // 刷新grid
        async refreshGrid () {
            this.searchParams.resourceId = this.projectId;
            const TRAINING_GET_URL = trainingUrlAdapter(`project/${this.projectId}/task/run`);
            let jsonData = await this.$ajax.get(TRAINING_GET_URL, this.searchParams);
            let table = this.$refs.updateTimeTable;
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                table.loadData([]);
                return;
            }
            if (!table) {
                return;
            }
            this.showEmptytraining = data.list.length === 0;
            let statusRunning = data.list.filter(item=>item.status === 1).length;
            if (!statusRunning) {
                this.intervalTask &&　this.intervalTask.stop();
                this.intervalTask = null;
            }
            table.loadData(data.list || []);
            table.getPagination().setTotal(data.total);
            this.trainingIdList = data.list.map(item=>item.jobKubeflowId);
        },

        //获取列表状态
        async _refreshTrainingStatus () {
            if (!this.trainingIdList.length) {
                return;
            }
            this.isGetTrainingStatus = true;
            let params = {
                jobList:this.trainingIdList
            };
            let jsonData = await this.$ajax.post(RUN_STATUS_URL, params);
            let {success, msg} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }

            this.refreshGrid();
        },
        dataHandler (data) {
            if (!Array.isArray(data)) {
                return [];
            }
            return data.map((item, index) => ({
                ...item,
                expanded:true,
                sequenceNo: index + 1,
                isTypeOfUser: true, // 树的第一层表示用户
                children: item.children || null
            }));
        },
        encodeTime (time) {
            return encodeDate(time);
        },
        repositoryStatusClass (status) {
            return REPOSITORY_STATUS_CLASS[status];
        },
        repositoryStatusText (status) {
            return REPOSITORY_STATUS_TEXT[status];
        },

        async ajaxDeleteModel (record) {
            const DELETE_URL = trainingUrlAdapter(`task/${record.id}`);
            this.$mask();
            let jsonData = await this.$ajax.delete(DELETE_URL, {runId:record.id});
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('删除成功'));
            this.refreshGrid();
        },
        _deleteModel (record) {
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}任务吗？', record.taskName),
                msg: _('删除后，操作无法撤回，请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteModel(record);
                    }
                }
            });
        },

         //更新模型，跳转到对应的aiFlow项目
        async _updateModel (record) {
            this.$mask();
            let query = deepClone(this.$route.query);
            this.$router.push({
                path:`/project_manager/data_load`,
                query:Object.assign(query, {aiFlowId:record.aiFlowId, flow_name:record.flowName, aiFlowType:record.aiFlowType})
            });
        },
        getAlgoParams (record) {
            if (!record) {
                return '参数：-';
            } 

            // let list = [];
            // jsons.forEach(item => {
            //     list.push(`${item.paramName} = ${item.value}`);
            // });
            return `参数：${record}`;
        },
        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },
        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },
        getTransformFieldList (obj) {
            let transformList = Object.keys(obj);
            let fieldList = [];
            fieldList = selectDataTransfrom(transformList);
            return fieldList;
        },
        _refresh () {
            this.refreshGrid();
        }
    },
    beforeDestroy () {
        if (this.intervalTask) {
            this.intervalTask.stop();
            this.intervalTask = null;
        }
    }
};
</script>
      